package com.wjk.kylin.id.core.spring.boot.autoconfigure.kid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wjk
 */
public class KylinIdInfoConfig {
    private List<String> serverList;
    private String token;
    private Double loadIdThreshold;
    private static final String URL = "http://{0}/kylin-id/info/ids";

    private static volatile KylinIdInfoConfig idInfoConfig;

    private KylinIdInfoConfig() {
    }


    /**
     * @param servers
     * @param token
     */
    public static void init(List<String> servers, String token, Double loadIdThreshold) {
        if (CollectionUtils.isEmpty(servers)) {
            throw new IllegalArgumentException("server is null");
        }
        if (StringUtils.isBlank(token)) {
            throw new IllegalArgumentException("token is null");
        }
        if (idInfoConfig == null) {
            synchronized (KylinIdInfoConfig.class) {
                if (idInfoConfig == null) {
                    idInfoConfig = new KylinIdInfoConfig();
                    idInfoConfig.setToken(token);
                    idInfoConfig.setLoadIdThreshold(loadIdThreshold == null ? 10 : loadIdThreshold);
                    //
                    List<String> serverList = new ArrayList<>();
                    for (String server : servers) {
                        String url = MessageFormat.format(URL, server);
                        serverList.add(url);
                    }
                    idInfoConfig.setServerList(serverList);
                }
            }
        }
    }

    /**
     * @return
     */
    public static KylinIdInfoConfig getInstance() {
        if (idInfoConfig == null) {
            throw new NullPointerException(KylinIdInfoConfig.class.getName() + "is null");
        }
        return idInfoConfig;
    }


    public List<String> getServerList() {
        return serverList;
    }

    public void setServerList(List<String> serverList) {
        this.serverList = serverList;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Double getLoadIdThreshold() {
        return loadIdThreshold;
    }

    public void setLoadIdThreshold(Double loadIdThreshold) {
        this.loadIdThreshold = loadIdThreshold;
    }

    @Override
    public String toString() {
        return "IdInfoConfig{" +
                "serverList=" + serverList +
                ", token='" + token + '\'' +
                ", loadIdThreshold=" + loadIdThreshold +
                '}';
    }
}
